<?php
session_start();
include("../include/util.inc.php");
$first_sql_section = true;

function composite_sql_with_and($sql){
    global $first_sql_section;
    if($first_sql_section){
        $first_sql_section = false;
    }else{
        $sql = $sql . " and";
    }
    return $sql;
}
function getQuestions($category, $level, $size, $property)
{
    try {
        $PDO = getPDO();

        $sql = "SELECT * FROM question WHERE";
        if ($category != 'random') {
            $sql = composite_sql_with_and($sql);
            $category = $PDO->quote($category);
            $sql = $sql . " `category` = $category";
        }

        if ($level != 4) {
            $sql = composite_sql_with_and($sql);
            $level = $PDO->quote($level);
            $sql = $sql . " `level` = $level";
        }

        $sql = composite_sql_with_and($sql);
        if($property == 'Public'){
            $sql = $sql . " `property` = 0";
        }else if($property == 'Private'){
            $tmp = $_SESSION['uid'];
            $sql = $sql . " `property` = $tmp";
        }else{
            $tmp = $_SESSION['uid'];
            $sql = $sql . " (`property` = 0 or `property` = $tmp)";
        }

        $sql = $sql . " ORDER BY RAND() limit $size";
        // echo $sql;

        $result = $PDO->query($sql);
        return $result;
    } catch (\PDOException $e) {
        throw new \PDOException($e->getMessage(), (int) $e->getCode());
    }
}

try {
    $questions = getQuestions($_GET["option1"], intval($_GET["option2"]), intval($_GET["option3"]), $_GET['property']);
    $rs = $questions->fetchAll(PDO::FETCH_BOTH);

    if(!isset($_GET['countdown'])){
        $_SESSION['countdown'] = null;
        $_SESSION['start_times'] = null;
        $_SESSION['end_times'] = null;
    }else{
        $_SESSION['countdown'] = intval($_GET['countdown']);
        $_SESSION['start_times'] = array();
        $_SESSION['end_times'] = array();
    }
    
    $question = array();
    $answer = array();
    for($i = 0; $i < count($rs); $i++){
        array_push($question, $rs[$i]['question']);
        array_push($answer, $rs[$i]['answer']);
    }

    $_SESSION['question'] = $question;
    $_SESSION['answer'] = $answer;
    $_SESSION['quiz_size'] = count($question);
    $_SESSION['user_input'] = array();
    $_SESSION['quiz_start_time'] = time();

    echo  json_encode(['question' => $question]) ;
} catch (\PDOException $e) {
    echo $e->getMessage();
}


?>